package tk.mynoteapp.dev.demo02.lockscope;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

/**
 * 加锁前要清楚锁和被保护的对象是不是一个层面的
 */
public class Interesting {
    private Logger logger = LoggerFactory.getLogger(Interesting.class);
    volatile int a = 1;
    volatile int b = 1;

    public synchronized void add() {
        logger.info("add start");
        for (int i = 0; i < 10000; i++) {
            a++;// ++操作不具有原子性
            b++;
        }
        logger.info("add done");
    }

    public void compare() {
        logger.info("compare start");
        for (int i = 0; i < 10000; i++) {
            if (a < b) {// a < b操作不具有原子性，JVM层面分为 load a, load b, compare a b
                logger.info("a:{}, b:{}, {}", a, b, a > b);
            }
        }
        logger.info("compare done");
    }

    public synchronized void compareRight() {
        logger.info("compare start");
        for (int i = 0; i < 10000; i++) {
            Assert.isTrue(a == b, "a != b");
            if (a < b) {
                logger.info("a:{}, b:{}, {}", a, b, a > b);
            }
        }
        logger.info("compare done");
    }
}
